package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.common.exception.BusinessException;
import com.atguigu.srb.core.enums.BorrowInfoStatusEnum;
import com.atguigu.srb.core.enums.LendStatusEnum;
import com.atguigu.srb.core.mapper.*;
import com.atguigu.srb.core.pojo.entity.*;
import com.atguigu.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.service.BorrowInfoService;
import com.atguigu.srb.core.service.LendService;
import com.atguigu.srb.core.util.DictUtils;
import com.atguigu.srb.core.util.LendNoUtils;
import com.atguigu.srb.core.util.LendUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author lsyandwh
 * @since 2022-12-02
 */
@Service
@Transactional
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private IntegralGradeMapper integralGradeMapper;

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private BorrowerMapper borrowerMapper;

    @Autowired
    private LendMapper lendMapper;

    @Override
    public Integer getBorrowerInfoStatus(String userId) {

        //1.根据用户id获取borrower_info表中用户状态
        QueryWrapper<BorrowInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);

        BorrowInfo borrowInfo = baseMapper.selectOne(wrapper);

        if(null != borrowInfo){
            return borrowInfo.getStatus();
        }
        //如果没有数据则返回默认值0
        return 0;
    }

    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, String userId) {

        //1.获取用户积分
        UserInfo userInfo = userInfoMapper.selectById(Long.parseLong(userId));
        Integer integral = userInfo.getIntegral();

        //2.根据积分判断用户借款额度
        QueryWrapper<IntegralGrade> wrapper = new QueryWrapper<>();
        wrapper.le("integral_start",integral)//小于区间
                .ge("integral_end",integral);//大于区间

        IntegralGrade integralGrade = integralGradeMapper.selectOne(wrapper);

        //3.判断用户借款额度是否满足
        //实际借款额度
        BigDecimal amount = borrowInfo.getAmount();
        //理论借款上限
        BigDecimal borrowAmount = integralGrade.getBorrowAmount();
        double practicalAmount = amount.doubleValue();
        double theoryAmount = borrowAmount.doubleValue();
        if(theoryAmount < practicalAmount){
            throw new BusinessException("实际借款额度超出理论借款额度");
        }

        //4.设置数据
        borrowInfo.setUserId(Long.parseLong(userId));
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        //转换小数
        borrowInfo.setBorrowYearRate( borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        //插入数据
        baseMapper.insert(borrowInfo);
    }

    @Override
    public List<BorrowInfo> getList() {

        //获取申请列表
        List<BorrowInfo> list = baseMapper.selectList(null);

        List<BorrowInfo> collect = list.stream().map(borrowInfo -> {

            //获取用户信息
            Long userId = borrowInfo.getUserId();
            UserInfo userInfo = userInfoMapper.selectById(userId);

            Map<String, Object> map = new HashMap<>();

            //获取节点信息
            String returnMethod = DictUtils.getDictName(dictMapper, "returnMethod", borrowInfo.getReturnMethod());
            String moneyUse = DictUtils.getDictName(dictMapper, "moneyUse", borrowInfo.getMoneyUse());
            map.put("returnMethod", returnMethod);
            map.put("moneyUse", moneyUse);
            map.put("status",BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus()));

            borrowInfo.setName(userInfo.getName());
            borrowInfo.setMobile(userInfo.getMobile());

            borrowInfo.setParam(map);
            return borrowInfo;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public Map<String, Object> gteBorrowInfoDetail(Long id) {

        //1.根据id查询borrowInfo详细信息
        BorrowInfo borrowInfo = baseMapper.selectById(id);

        Map<String, Object> map = new HashMap<>();

        //设置节点信息
        String returnMethod = DictUtils.getDictName(dictMapper, "returnMethod", borrowInfo.getReturnMethod());
        String moneyUse = DictUtils.getDictName(dictMapper, "moneyUse", borrowInfo.getMoneyUse());
        map.put("returnMethod", returnMethod);
        map.put("moneyUse", moneyUse);
        map.put("status",BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus()));

        borrowInfo.setParam(map);

        //2.查询借款人详细信息
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",borrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(wrapper);

        BorrowerDetailVO borrowerDetailVO = new BorrowerDetailVO();
        BeanUtils.copyProperties(borrower,borrowerDetailVO);
        //查询借款人节点信息
        borrowerDetailVO.setStatus(BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus()));
        borrowerDetailVO.setIndustry(DictUtils.getDictName(dictMapper,"industry",borrower.getIndustry()));
        borrowerDetailVO.setEducation(DictUtils.getDictName(dictMapper,"education",borrower.getEducation()));
        borrowerDetailVO.setIncome(DictUtils.getDictName(dictMapper,"income",borrower.getIncome()));
        borrowerDetailVO.setReturnSource(DictUtils.getDictName(dictMapper,"returnSource",borrower.getReturnSource()));
        borrowerDetailVO.setContactsRelation(DictUtils.getDictName(dictMapper,"relation",borrower.getContactsRelation()));
        borrowerDetailVO.setSex(borrower.getSex() == 1 ? "男" : "女");
        borrowerDetailVO.setMarry(borrower.getMarry() ? "是" : "否");

        Map<String,Object> result = new HashMap<>();
        result.put("borrowInfo",borrowInfo);
        result.put("borrower",borrowerDetailVO);

        return result;
    }

    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {

        //更新BorrowInfo表中的状态
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoApprovalVO.getId());
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        baseMapper.updateById(borrowInfo);

        //审核通过则创建标的
        if (borrowInfoApprovalVO.getStatus().intValue() == 2) {
            //创建标的
            Lend lend = LendUtils.createLend(borrowInfo, borrowInfoApprovalVO);

            lendMapper.insert(lend);
        }
    }
}
